package com.bsdk.install.device.driver.mqtt;

import com.alibaba.fastjson2.JSONObject;
import com.bsdk.common.core.domain.AjaxResult;
import com.bsdk.common.utils.DateUtils;
import com.bsdk.install.domain.DeviceCmd;
import com.bsdk.install.mqtt.MqttPushClient;
import com.bsdk.install.service.IDeviceCmdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class MqttSendCmd {
    private final String topicDown = "server/gateway/";
    @Autowired
    private MqttPushClient mqttPushClient;
    @Autowired
    private IDeviceCmdService deviceCommLogService;

    public AjaxResult send(JSONObject jsonObject) {

        DeviceCmd deviceCommLog = new DeviceCmd();
        deviceCommLog.setDevId(jsonObject.getString("devId"));
        deviceCommLog.setType("down");
        deviceCommLog.setCreateTime(DateUtils.getNowDate());
        deviceCommLog.setUid(jsonObject.getString("uId"));
        deviceCommLog.setData(jsonObject.toJSONString());
        deviceCommLogService.save(deviceCommLog);

        int qos = 0;
        boolean retained = true;
        String topic = this.topicDown + jsonObject.getString("devId") + "/";

        AjaxResult ajaxResult = mqttPushClient.publish(qos, retained, topic, jsonObject.toJSONString());

        if (ajaxResult.isSuccess()) {

            return AjaxResult.success("Mqtt通讯下发成功");

        } else {
            return AjaxResult.error("Mqtt通讯下发失败");
        }

    }


}
